package com.lzl.educenter.controller;

import com.google.gson.Gson;
import com.lzl.common_utils.JwtUtils;
import com.lzl.educenter.entity.UcenterMember;
import com.lzl.educenter.service.UcenterMemberService;
import com.lzl.educenter.utils.ConstantWxUtils;
import com.lzl.educenter.utils.HttpClientUtils;
import com.lzl.servicebase.exceptionHandler.LZLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

//@CrossOrigin
//@RestController   不能返回json数据
@Controller  //只是请求地址，不返回数据
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    //生成微信扫码二维码
    //之前controller返回的都是 R 对象，统一返回结果，按格式返回json数据
    //现在并不是返回数据，而是生成二维码，请求固定地址
    @GetMapping("login")
    public String getWxCode(){
        //固定地址，后面拼接参数
        /* 这种方式非常麻烦，且容易出错
        String url = "https://open.weixin.qq.com/" +
                "connect/qrconnect?appid="+ ConstantWxUtils.WX_OPEN_APP_ID+"&response_type=code"+...
                */

        // 微信开放平台授权baseUrl %s 相当于？代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行urlEncode编码        ---请使用urlEncode对链接进行处理
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        //生成qrcodeUrl--设置%s里面的值
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");

        //现在用重定向请求微信地址
        return "redirect:"+qrcodeUrl;
    }

    /**
     * 获取扫码成功后的 用户人信息
     * eg:路径：http://localhost:8160/api/ucenter/wx/callback?code=081bnill25HwW842Q8ml28H2Qb1bnilC&state=atguigu
     * @param code
     * @param state
     * @return
     */
    @GetMapping("callback")
    public String callback(String code,String state){

        //获取code值，临时票据，类似于验证码
        System.out.println("code==="+code);
        System.out.println("state=="+state);
        //拿着code请求，微信固定的地址，得到两个值access_token 和 openid
        String baseAccessTokenUrl =
                "https://api.weixin.qq.com/sns/oauth2/access_token" +
                        "?appid=%s" +
                        "&secret=%s" +
                        "&code=%s" +
                        "&grant_type=authorization_code";
        //拼接三个参数： id 密钥 和code值
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code);

        //请求拼接好的地址，得到返回两个值  access_token 和 openid
        //不能直接请求到页面，程序还需要继续执行-得到用户信息--使用httpClient发送请求-得到返回结果
        String accessTokenInfo = null;
        try {
             accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

        } catch (Exception e) {
           throw new LZLException(20001,"获取access_token失败");
        }
        //返回的值 是json字符串的格式
        System.out.println("accessTokenInfo=="+accessTokenInfo);
        //把accessTokenInfo字符串转换成map集合，根据map里面的key获取对应着
        //使用json转换工具--gson
        Gson gson = new Gson();
        HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
        String access_token = (String) mapAccessToken.get("access_token");
        String openid = (String) mapAccessToken.get("openid");
        System.out.println("access_token=="+access_token);
        System.out.println("openid=="+openid);

        //把扫描人信息添加数据库里面
        //判断数据库里面是否存在相同的微信信息数据--根据微信唯一标识--openid
        UcenterMember member = ucenterMemberService.getOpenIdMember(openid);
        if (member == null) {  //member是空，表里没有相同的微信数据，进行添加
            //拿着得到的access_token 和 openid，再去请求微信提供的固定的api地址，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            //拼接两个参数
            String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);

            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
            } catch (Exception e) {
                throw new LZLException(20001,"获取用户信息失败");
            }
            System.out.println("resultUserInfo==========" + resultUserInfo);

            //解析json, 获取字符串扫描的用户信息
            HashMap<String, Object> mapUserInfo = gson.fromJson(resultUserInfo, HashMap.class);
            String nickname = (String)mapUserInfo.get("nickname");  //昵称
            String headimgurl = (String)mapUserInfo.get("headimgurl");  //头像

            member = new UcenterMember();
            member.setOpenid(openid);
            member.setNickname(nickname);
            member.setAvatar(headimgurl);
            ucenterMemberService.save(member);
        }

        //使用jwt根据member对象生成token字符串
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());


        //最后：返回首页面,通过路径传递token字符串
        return "redirect:http://localhost:3000?token="+jwtToken;
    }

}
